<?php

namespace app\api\controller;


use app\common\controller\Api;
use app\common\library\Auth;
use app\common\model\UserSelect;
use think\Cache;
use think\Db;
use think\Request;

class Marketlist extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 涨幅获取
     * @ApiMethod (GET)
     * @param string $like 用户输入
     */

    public function getStockRank($type = 1, $number = 30)
    {
        $redis = Cache::store('redis')->handler();
        $hashObject = $redis->hGetAll('stock:hash:pricelist');

        // 存储股票信息的数组
        $stocks = [];

        foreach ($hashObject as $key =>  $value) {
            $value = explode('|', $value);
            $key = explode('|', $key);

            $numbering =  $key[0]; //编号  
            $name = $value[1];   //名字
            $price = $value[2];  //价格

            $change = floatval($value[3]); // 将涨跌幅转换为浮点数进行比较

            if ($type == 1 && $change > 0) {
                $stocks[] = ['numbering' => $numbering, 'name' => $name, 'price' => $price, 'change' => $change]; // 涨幅榜
            } elseif ($type == 2 && $change < 0) {
                $stocks[] = ['numbering' => $numbering, 'name' => $name, 'price' => $price, 'change' => $change]; // 跌幅榜
            }
        }

        // 取出前 $number 个股票信息
        $result = array_slice($stocks, 0, $number);

        // 关闭Redis连接
        $redis->close();
        // 返回结果
        $this->success('获取成功', $result);
    }



    /**
     * 股票热门榜
     * @ApiMethod (GET)
     * @param string $like 用户输入
     */
    public function StockHotList($number = 20)
    {
        $cacheExpire = 600; 

        // 尝试从缓存中读取数据
        $stocks = Cache::store('redis')->get('stock:hotlist');

        if ($stocks === false) {
            // 如果缓存不存在，则重新查询数据并进行缓存

            $sql = "SELECT `all_no`,COUNT(*) c FROM `sx_user_select` GROUP BY `all_no` ORDER BY c DESC LIMIT $number";
            $data = Db::query($sql);
            if( !$data ){
                $sql = "SELECT `all_no`,`id` FROM `sx_stock` limit $number";
                $data = Db::query($sql);
            }
            // 存储股票信息的数组
            $stocks = [];

            $redis = Cache::store('redis')->handler();
            $hotlist = $redis->hGetAll('stock:hash:pricelist');

            foreach ($data as $key => $rows) {
                $code = $rows['all_no'];
                $stockinfo = explode('|', $hotlist[$code]);

                $stocks[$key] = [
                    'code' => $code,
                    'name' => $stockinfo[1],
                    'price' => $stockinfo[2],
                    'change' => $stockinfo[3],
                ];
            }

            // 对数据进行缓存
            Cache::store('redis')->set('stock:hotlist', $stocks, $cacheExpire);
        }

        // 取出前 $number 个股票信息
        $result = array_slice($stocks, 0, $number);
        $this->success('获取成功', $result);
    }

    /**
     * 自选接口
     */
    public function optional()
    {

        $userInfo = $this->auth->getUser();
        if (!isset($userInfo)) {
            $this->error('用户未登录或没有数据');
            exit;
        }
        $data = Db::name('user_select')->where(['user_id' => $userInfo->id])->select();
        $newData = [];

        $redis = Cache::store('redis')->handler();
        $exponentlist = $redis->hGetAll('stock:hash:pricelist');

        foreach ($data as $key => $rows) {
            $code = $rows['all_no'];
            $stockinfo = explode('|', $exponentlist[$code]);

            $newData[$key] = [
                'code' => $code,
                'name' => $rows['name'],
                'price' => $stockinfo[2],
                'change' => $stockinfo[3],
            ];
        }

        $this->success('获取成功', $newData);
    }

    //获取股票信息
    protected function stockInfo($data)
    {
        $returnData = getStockInfo($data);
        return $returnData;
    }

    /**
     * 添加接口
     */

    public function addSelect()
    {
        $userInfo = $this->auth->getUser();
        $allNo = $this->request->post('all_no');
        $userSelectInfo = UserSelect::where(['all_no' => $allNo, 'user_id' => $userInfo->id])->find();
        if ($userSelectInfo) {
            $this->error('股票已添加自选');
        }
        $stockInfoArr = $this->stockInfo($allNo);
        if (!isset($stockInfoArr[$allNo])) {
            // 不存在索引为 $allNo 的元素，处理错误逻辑
            $this->error('股票信息不存在');
        }

        $stockInfo = $stockInfoArr[$allNo];
        UserSelect::create([
            'user_id' => $userInfo->id,
            'all_no' => $stockInfo['all_no'],
            'name' => $stockInfo['name'],
        ]);
        $this->success('添加成功');
    }

    /**
     * 删除接口
     */
    public function delSelect()
    {
        $userInfo = $this->auth->getUser();
        $id = $this->request->post('id');
        $userSelectInfo = UserSelect::where(['id' => $id, 'user_id' => $userInfo->id])->find();
        if (!$userSelectInfo) {
            $this->error('没有找到自选股票');
        }
        $userSelectInfo->delete();
        $this->success('删除成功');
    }

    
}
